package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.constants.wemedia.message.NewsAutoScanConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wenmedia.dtos.NewsAuthDTO;
import com.heima.model.wenmedia.dtos.WmNewsDTO;
import com.heima.model.wenmedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wenmedia.pojos.WmNews;
import com.heima.model.wenmedia.pojos.WmNewsMaterial;
import com.heima.model.wenmedia.pojos.WmUser;
import com.heima.model.wenmedia.vo.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        // 1. 校验参数  分页  登录
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2. 封装查询条件
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery();
        // 标题模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())){
            wrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        // 频道查询
        if (dto.getChannelId() != null){
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        // 状态
        if (dto.getStatus() != null){
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        // 时间区间查询   开始时间
        if(dto.getBeginPubDate() != null && dto.getEndPubDate() !=null){
            wrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        // 用户id
        wrapper.eq(WmNews::getUserId,user.getId());
        wrapper.orderByDesc(WmNews::getCreatedTime);
        // 3. 执行分页查询
        Page<WmNews> pageReq = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmNews> pageResult = this.page(pageReq, wrapper);
        // 4. 封装响应结果   host: 图片访问前缀
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal(),pageResult.getRecords());
        pageResponseResult.setHost(webSite);
        return pageResponseResult;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        // 1. 将dto转化为wmnews对象
        // 1.1 校验参数  (content  登录)
        if (StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章内容不能为空");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 1.2 将dto的属性值拷贝wmNews对象
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        // 1.3 如果type等于-1 ， 暂时设置type为null
        if(WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            wmNews.setType(null);
        }
        // 1.4 封面dto传入的是List<String> 图片集合  转化为字符串用逗号拼接
        if(CollectionUtils.isNotEmpty(dto.getImages())){
            String imageStr = imagesToStr(dto.getImages());
            wmNews.setImages(imageStr);
        }else {
            wmNews.setImages(null);
        }
        // 登录人id
        wmNews.setUserId(user.getId());
        // 2. 保存或修改wmNews对象
        saveOrUpdateWmNews(wmNews);
        if(WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())){
            return ResponseResult.okResult();
        }
        // 3. 保存 文章内容或封面 和  素材的关联关系
        // 3.1 抽取出内容中所有的素材url路径集合
        List<Map> contentMap = JSON.parseArray(dto.getContent(), Map.class);
        List<String> contentUrls = parseContentImages(contentMap);
        // 3.2 保存文章内容 和 素材的 关联关系
        if(CollectionUtils.isNotEmpty(contentUrls)){
            saveRelativeInfo(contentUrls,wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
        }
        // 3.3 保存文章封面 和 素材的 关联关系
        saveRelativeInfoForCover(contentUrls,wmNews,dto);

        // 4. 发送自动审核消息 到mq
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("已成功发送 文章自动审核消息   消息内容:{}",wmNews.getId());

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if(id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if(enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable)&&!WemediaConstants.WM_NEWS_DOWN.equals(enable))){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，同步到app端（后期做）TODO
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
                .set(WmNews::getEnable,dto.getEnable()));
        if (wmNews.getArticleId()!=null) {
            if(enable.equals(WemediaConstants.WM_NEWS_UP)){
                // 上架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
            }else {
                // 下架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,wmNews.getArticleId());
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        // 1. 校验参数   分页数据
        dto.checkParam();
        Integer page = dto.getPage();
        dto.setPage((page - 1) * dto.getSize());
        // 2. 执行条件分页查询
        List<WmNewsVO> listAndPage = wmNewsMapper.findListAndPage(dto);
        long listCount = wmNewsMapper.findListCount(dto);
        // 3. 返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(page,dto.getSize(),listCount,listAndPage);
        pageResponseResult.setHost(webSite);
        return pageResponseResult;
    }


    @Autowired
    WmUserMapper wmUserMapper;

    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 自媒体文章人工审核
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        // TODO 通知定时发布文章

        //通知定时发送文章
        //1.获取发送的时间
        long publishTime = wmNews.getPublishTime().getTime();
        //2.获取当前时间
        long currentTimeMillis = System.currentTimeMillis();
        //3.时间差
        long remainTime = publishTime - currentTimeMillis;
        //4.发消息
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE, PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,
                wmNews.getId(),
                message -> {
                    (message).getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;

                });

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存文章封面 和 素材的 关联关系
     * @param contentUrls
     * @param wmNews
     */
    private void saveRelativeInfoForCover(List<String> contentUrls, WmNews wmNews,WmNewsDTO dto) {
        // 1. 前端传入的封面集合   （有前缀）
        List<String> images = dto.getImages();
        // 2. 判断dto type是否为 -1   ，需要生成封面
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            // 说明内容无图片
            if(CollectionUtils.isEmpty(contentUrls)){
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }else if(contentUrls.size()>0 && contentUrls.size() <= 2){
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = contentUrls.stream().limit(1).collect(Collectors.toList());
            }else {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = contentUrls.stream().limit(3).collect(Collectors.toList());
            }

            if(CollectionUtils.isNotEmpty(images)){
                wmNews.setImages(imagesToStr(images));
            }
            // 修改wmNews
            updateById(wmNews);
        }
        if(CollectionUtils.isNotEmpty(images)){
            images = images.stream().map(url -> url.replaceAll(webSite,""))
                    .distinct().collect(Collectors.toList());
            // 3. 保存封面和素材的关联关系
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);
        }

    }

    @Autowired
    WmMaterialMapper wmMaterialMapper;

    /**
     * 保存素材 和 文章的关联关系
     *
     * @param materialUrls 素材路径集合
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> materialUrls, Integer newsId, Short type) {
        // 1. 根据图片路径列表 及 登录用户id 查询相关素材id
        Integer userId = WmThreadLocalUtils.getUser().getId();
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(materialUrls, userId);
        // 2. 检查 id 的数量 是否小于 url集合的size, 如果小于代表素材缺失 抛异常
        if(ids.size() < materialUrls.size()){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"引用的素材已经失效");
        }
        // 3. 批量保存关联关系  使用foreach批量插入
        wmNewsMaterialMapper.saveRelations(ids,newsId,type);
    }

    /**
     * [{type: text,value:xxxsadas},{type: image, value: 前缀 + 路径},{}]
     * @param contentMap
     * @return
     */
    private List<String> parseContentImages(List<Map> contentMap) {
        return contentMap.stream()
                // 过滤 type为image的数据
                .filter(m -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(m.get("type")))
                // 取出 map中的url路径
                .map(m -> m.get("value").toString())
                // 去除前缀路径
                .map(url -> url.replaceAll(webSite,""))
                // 去除重复
                .distinct()
                // 收集
                .collect(Collectors.toList());
    }


    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 保存 或 修改文章
     *
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        // 1. 将wmNews对象信息补全
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        // 默认上架
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        // 2. 判断是否携带id
        if(wmNews.getId() == null){
            // 2.1 如果没有id 就保存
            save(wmNews);
        }else {
            // 2.2 如果有id   先删除关联关系  在修改
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }
    }

    /**
     *
     *
     * @param images
     * @return
     */
    private String imagesToStr(List<String> images) {
        // 创建流
        return images.stream()
                // 去除前缀路径
                .map(url -> url.replaceAll(webSite,""))
                // 去除重复
                .distinct()
                // 逗号拼接
                .collect(Collectors.joining(","));
    }
}